package com.zanglikun.rocketmq.base;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.util.List;

/**
 * @Author: zanglikun
 * @Date: 2022/3/31 18:03
 * @Description: 负载均衡消息接受者, 注意对象是Push 这是”拉“模式消费
 */
public class BroadcastConsumer {
    public static void main(String[] args) throws Exception {
        // todo 1 创建消费者，同时指定消费组
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group1");
        // todo 2 指定NameServer
        consumer.setNamesrvAddr("192.168.253.128:9876;192.168.253.129:9876");
        // todo 3 订阅主题
        consumer.subscribe("base","Tag1");
        // todo 4 设定BROADCASTING 广播模式。默认是CLUSTERING,也就是负载均衡
        consumer.setMessageModel(MessageModel.BROADCASTING);
        //consumer.setMessageModel(MessageModel.CLUSTERING);
        // todo 5 设置回调函数，以处理消息
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                //System.out.println(list);
                list.forEach(messageExt ->{
                    System.out.println(new String(messageExt.getBody()));
                });
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        // todo 5 启动消费者
        consumer.start();
    }
}
